﻿#include "pwm30120.h"
#include <QDebug>
PWM30120::PWM30120()
{
    serialPort = new QSerialPort();
    serialPort->setPortName("COM3");
    if(!serialPort->open(QIODevice::ReadWrite))//用ReadWrite 的模式尝试打开串口
    {
        qDebug() << "open() fail";
        return;
    }
    serialPort->setBaudRate(QSerialPort::Baud9600,QSerialPort::AllDirections);//设置波特率和读写方向
    serialPort->setDataBits(QSerialPort::Data8);		//数据位为8位
    serialPort->setFlowControl(QSerialPort::NoFlowControl);//无流控制
    serialPort->setParity(QSerialPort::NoParity);	//无校验位
    serialPort->setStopBits(QSerialPort::OneStop); //一位停止位
}

PWM30120::~PWM30120()
{
    serialPort->close();
    delete serialPort;
}

int PWM30120::value(int channel)
{
    return m_value[channel];
}

bool PWM30120::setValue(int channel, int intensity)
{
    if(channel < 0 || channel >= 4)
    {
        return false;
    }
    m_value[channel] = intensity;

    unsigned char buf[] = {0xA9, 0x0B, 0x00, 0x00, 0x00, 0x00};
    buf[1] = 0x0A + channel;
    buf[3] = intensity;
    buf[5] = buf[0] ^ buf[1] ^ buf[2] ^ buf[3] ^ buf[4];

    qDebug() << buf[0] << buf[1] << buf[2] << buf[3] << buf[4] << buf[5];
    int ret = serialPort->write((char *)buf, 6);
    if(ret == -1)
    {
        return false;
    }
    return true;
}

bool PWM30120::valueRange(int channel, int &min, int &max)
{
    Q_UNUSED(channel);
    min = 0;
    max = 255;
    return true;
}

bool PWM30120::setEnable(int channel, bool on)
{
    if(!on)
    {
        unsigned char buf[] = {0xA9, 0x0B, 0x00, 0x00, 0x00, 0x00};
        buf[1] = 0x0A + channel;
        buf[5] = buf[0] ^ buf[1] ^ buf[2] ^ buf[3] ^ buf[4];

        int ret = serialPort->write((char *)buf, 6);
        if(ret == -1)
        {
            return false;
        }
        return true;
    }
    return setValue(channel, m_value[channel]);
}
